import axios from "axios";
import store from "../store";
import ENV from "./env";

import { getToken, getWxAuth } from "./auth";

// 创建axios实例
const service = axios.create({
  baseURL: ENV.BASE_API, // api的base_url
  timeout: 100000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    const token = getToken();
    config.headers["Authorization"] = `Bearer ${token}`;
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  (error) => {
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 4 || response.data.code === 1404) {
      store.dispatch("LogOut").then(() => {
        getWxAuth();
      });
      return Promise.reject();
    } else if (response.data.code === 0) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response.data.msg);
    }
  },
  (error) => {
    // alert(error)
    console.log("err" + error); // for debug
    return Promise.resolve(error);
  }
);

export default service;
